package cn.cheegon.blog.service.impl;

import cn.cheegon.blog.common.exception.Asserts;
import cn.cheegon.blog.service.FileService;
import com.alibaba.fastjson.JSONException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @Desc: 文件处理类
 * @Author: cheegon
 * @Date: Create in 2024/6/26  上午10:25
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Value("${upload.path}")
    private String uploadDir;
    @Value("${upload.server}")
    private String remoteUrl;
    @Override
    public String uploadImage(MultipartFile file) {
        if (file.isEmpty()) {
            Asserts.fail("文件不能为空");
        }
        try {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            // 提取文件后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成一个唯一的文件名
            String newFileName = UUID.randomUUID() + suffix;
          //  save2Local(file,newFileName);
            save2Destination(file,newFileName);
            return "/upload/" + newFileName;
            // return ServletUriComponentsBuilder.fromCurrentContextPath().path("/upload/images/").path(newFileName).toUriString();
        } catch (IOException | JSONException e) {
            System.out.println(e.toString());
        }
        Asserts.fail("上传图片失败");
        return "";
    }
    private void save2Destination(MultipartFile file,String newFileName) throws IOException{
//        JSONObject postData = new JSONObject();
//        byte[] fileBytes = file.getBytes();//转换为byte数组
//        postData.put("fileName",newFileName);
//        postData.put("data",fileBytes);
//        RestTemplate restTemplate = new RestTemplate();
//        //FilePath是你服务端的项目接口路径
//        String response = restTemplate.postForObject(remoteUrl, file, String.class);
        Client client = Client.create();
        WebResource webResource = client.resource(remoteUrl + newFileName);
        webResource.put(file.getBytes());
    }
    private void save2Local(MultipartFile file,String newFileName) throws IOException{
        Path uploadPath = Paths.get(uploadDir);
        // 如果上传文件夹不存在，创建该文件夹
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        File dest = new File(uploadPath.toFile().getAbsolutePath(), newFileName);//空文件
        file.transferTo(dest);
    }
}
